package com.chen.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.chen.reggie.common.BaseContext;
import com.chen.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @ClassName LoginCheckFilter
 * @Description 检查用户是否已经完成登录
 * @Author hainc
 * @Date 2022/9/4 14:20
 * @Version 1.0
 *
 **/
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，让/**通配符生效
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();
        log.info("本次请求{}",requestURI);

        //放行的路径
        final String[] urls = {"/employee/login", "/employee/logout", "/backend/**", "/front/**","/common/**","/user/sendMsg","/user/login","/doc.html","/webjars/**","/swagger-resources","/v2/api-docs"};
        boolean check = check(urls, requestURI);

        //放行静态资源和登录登出请求
        if(check){
            filterChain.doFilter(request,response);
            log.info("本次放行的请求{}",requestURI);
            return;
        }

        //4-1.判断后台用户登录，如果employee对象存在，代表已经登录，放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，id为：{}",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);//保存用户id到线程变量
            filterChain.doFilter(request,response);
            return;
        }

        //4-2.判断前台用户登录
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);//保存用户id到线程变量
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        //如果没有登录则返回跳转,返回前端定义的跳转对象
        //前端需要R.error("notlogin")对象判断是否没有登录，来进行跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    //路径匹配，检查本次请求是否放行
    public boolean check(String [] urls,String requestURI){
        for(String url : urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
